package com.cms.pms.impl;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.cms.pms.PMSContext;
import com.cms.pms.Processor;
import com.cms.pms.Store;

public class ProcessorImpl implements Processor {

	Timer timer = new Timer();

	boolean isRunning = false;
	
	int interval = 10000;
	
	public int getInterval() {
		return interval;
	}

	public void setInterval(int interval) {
		this.interval = interval;
	}

	@Override
	public void start() {
		if (!isRunning) {
			timer.schedule(new Task(), 1000, interval);
			isRunning = true;
		}
	}

	@Override
	public void stop() {
		if (isRunning) {
			timer.cancel();
			isRunning = false;
		}
	}

	class Task extends TimerTask {

		@Override
		public void run() {
			PMSContext.getAggregator().prepare();
			
			Map<Thread, Store> map = PMSContext.getAllStore();
			for (Store s : map.values()) {
				for (;;) {
					Object obj = s.take();
					if (obj == null)
						break;
					PMSContext.getAggregator().handle(obj);
				}
			}
			
			PMSContext.getAggregator().aggregate();
			
			Map<Thread, Store> storemap = PMSContext.getAllStore();
			for(Thread t : storemap.keySet())
			{
				if(!t.isAlive())
					storemap.remove(t);
			}
			
		}
	}
	
	@Override
	public boolean isRunning() {
		return isRunning;
	}

}
